from django.shortcuts import render, HttpResponse

from django.core.mail import send_mail
from django.conf import settings
import random

def send_sms(request):
    """发送邮件"""
    # 拿到用户传入的邮箱地址 http://127.0.0.1:8080/send_sms/?mail=3944472124@qq.com
    # 1 取出前端传入的邮箱地址
    mail = request.GET.get('mail')

    # 生成 10000 到 99999 之间的随机整数
    random_five_digit = random.randint(10000, 99999)
    print(random_five_digit)

    # 2 发送邮件
    res = send_mail('xx网址登录验证码', '验证码为：{}'.format(random_five_digit), settings.EMAIL_HOST_USER, [mail, ])
    print('res=',res)
    return HttpResponse('邮件已经发送')

from django import  forms
from app01 import models
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError

class RegisterModelFrom(forms.ModelForm):

    # 重写 进行添加规则 校验

    # 正则表达式 RegexValidator
    mobile_phone = forms.CharField(label='手机号',validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ])

    # forms.PasswordInput() 表单密文 展示
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput())
    confirm_password = forms.CharField(
        label='重复密码',
        widget=forms.PasswordInput())

    code = forms.CharField(
        label='验证码',
        widget=forms.TextInput())

    class Meta:
        model = models.UserInfo
        fields = ['username', 'mobile_phone', 'password', 'confirm_password', 'email', 'code']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)


def register(request):
    form = RegisterModelFrom()
    return render(request, 'app01/register.html', {'form':form})


